package com.kjlink.internal.workreport.task;

import cn.xuqiudong.common.base.vo.BooleanWithMsg;
import com.kjlink.internal.workreport.helper.ReportCommonHelper;
import com.kjlink.internal.workreport.project.model.Project;
import com.kjlink.internal.workreport.task.handler.ProjectTimeStatsHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StopWatch;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 描述:
 * 基于项目的工时统计
 *
 * @author Vic.xu
 * @since 2024-05-27 13:32
 */
@Component
@Deprecated
public class ProjectTimeStatsTask implements CommandLineRunner {

    private static final Logger LOGGER = LoggerFactory.getLogger(ProjectTimeStatsTask.class);

    @Resource
    private ProjectTimeStatsHandler projectTimeStatsHandler;


    /**
     * 项目启动的时候 也执行一次统计
     */
    @Override
    public void run(String... args) throws Exception {
//        statistics();
    }

    /**
     * 23点59分50秒执行一次统计
     */
    @Scheduled(cron = "50 59 23 * * *")
    public void statistics() {

        List<Project> projects = projectTimeStatsHandler.noneClosedProjects();
        if (CollectionUtils.isEmpty(projects)) {
            LOGGER.info("没有项目需要统计工时");
            return;
        }
        StopWatch watch = new StopWatch();
        watch.start();
        LOGGER.info("start statistics project work times, project size = {}", projects.size());
        LocalDateTime now = LocalDateTime.now();
        int year = now.getYear();
        int month = now.getMonthValue();
        //形如202401  202412
        int monthDate = ReportCommonHelper.toMonthDate(year, month);
        projects.forEach(project -> {
            //1. 统计总工时
            BooleanWithMsg total = projectTimeStatsHandler.updateTotalTime(project);
            //2. 统计年工时
            BooleanWithMsg yearTime = projectTimeStatsHandler.updateYearUsedTime(project, year);
            //3. 统计月工时
            BooleanWithMsg monthTime = projectTimeStatsHandler.updateMonthUsedTime(project, year, month, monthDate);
            LOGGER.info("统计项目[{}]的总工时为[{}]小时,年工时为[{}]小时,月工时为[{}]小时", project.getName(), total.getMessage(), yearTime.getMessage(), monthTime.getMessage());
        });
        watch.stop();
        LOGGER.info("statistics project work times finished, total size = {}, total time = {}s", projects.size(), watch.getTotalTimeSeconds());


    }


}